<template>
  <div class="template-import">
    <el-form :model="importForm" :rules="rules" ref="importForm" label-width="100px">
      <!-- 导入方式选择 -->
      <el-form-item label="导入方式">
        <el-radio-group v-model="importForm.importType" @change="handleImportTypeChange">
          <el-radio label="file">文件导入</el-radio>
          <el-radio label="json">JSON数据</el-radio>
          <el-radio label="url">URL导入</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 文件导入 -->
      <div v-if="importForm.importType === 'file'" class="import-section">
        <el-form-item label="模板文件" prop="file">
          <el-upload
            ref="fileUpload"
            class="template-upload"
            action=""
            :auto-upload="false"
            :multiple="false"
            :show-file-list="true"
            :file-list="fileList"
            :on-change="handleFileChange"
            :on-remove="handleFileRemove"
            accept=".json,.txt,.template"
          >
            <el-button size="small" type="primary" icon="el-icon-upload">
              选择文件
            </el-button>
            <div slot="tip" class="el-upload__tip">
              支持 JSON、TXT 格式的模板文件，大小不超过 10MB
            </div>
          </el-upload>
        </el-form-item>
      </div>

      <!-- JSON数据导入 -->
      <div v-if="importForm.importType === 'json'" class="import-section">
        <el-form-item label="JSON数据" prop="jsonData">
          <el-input
            type="textarea"
            v-model="importForm.jsonData"
            :rows="12"
            placeholder="请粘贴模板的JSON配置数据..."
            resize="vertical"
          ></el-input>
        </el-form-item>
        
        <div class="json-actions">
          <el-button size="mini" @click="formatJSON" icon="el-icon-s-operation">
            格式化
          </el-button>
          <el-button size="mini" @click="clearJSON" icon="el-icon-delete">
            清空
          </el-button>
          <el-button size="mini" @click="loadExample" icon="el-icon-document">
            加载示例
          </el-button>
        </div>
      </div>

      <!-- URL导入 -->
      <div v-if="importForm.importType === 'url'" class="import-section">
        <el-form-item label="模板URL" prop="url">
          <el-input
            v-model="importForm.url"
            placeholder="请输入模板文件的URL地址..."
          >
            <template slot="prepend">HTTP</template>
          </el-input>
        </el-form-item>
        
        <el-form-item label="认证信息">
          <el-input
            v-model="importForm.authToken"
            placeholder="可选的认证令牌（如果需要）"
            style="width: 300px"
          ></el-input>
        </el-form-item>
      </div>

      <!-- 导入选项 -->
      <el-form-item label="导入选项">
        <el-checkbox-group v-model="importForm.options">
          <el-checkbox label="override">覆盖同名模板</el-checkbox>
          <el-checkbox label="validate">验证模板结构</el-checkbox>
          <el-checkbox label="includeData">包含示例数据</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 模板预览 -->
      <el-form-item label="模板预览" v-if="previewData">
        <el-collapse v-model="activePreview">
          <el-collapse-item title="模板信息预览" name="preview">
            <div class="preview-info">
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="模板名称">
                  {{ previewData.name || '未命名' }}
                </el-descriptions-item>
                <el-descriptions-item label="模板类型">
                  <el-tag :type="getTemplateTypeTag(previewData.type)" size="small">
                    {{ getTemplateTypeText(previewData.type) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="页面尺寸">
                  {{ previewData.pageSize || 'A4' }}
                </el-descriptions-item>
                <el-descriptions-item label="组件数量">
                  {{ (previewData.components || []).length }} 个
                </el-descriptions-item>
              </el-descriptions>
              
              <div v-if="previewData.components" class="components-preview">
                <h4>组件列表</h4>
                <el-table
                  :data="previewData.components"
                  size="mini"
                  style="width: 100%"
                  max-height="200"
                >
                  <el-table-column prop="type" label="类型" width="100">
                    <template #default="scope">
                      <el-tag size="small">{{ getComponentTypeText(scope.row.type) }}</el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column prop="position" label="位置" width="150">
                    <template #default="scope">
                      {{ scope.row.position.x }}, {{ scope.row.position.y }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="position" label="尺寸" width="100">
                    <template #default="scope">
                      {{ scope.row.position.width }}×{{ scope.row.position.height }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="content" label="内容预览">
                    <template #default="scope">
                      <span class="content-preview">
                        {{ getContentPreview(scope.row) }}
                      </span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </el-form-item>

      <!-- 验证结果 -->
      <el-form-item v-if="validationResult" label="验证结果">
        <div :class="['validation-result', validationResult.valid ? 'success' : 'error']">
          <i :class="validationResult.valid ? 'el-icon-success' : 'el-icon-error'"></i>
          <span>{{ validationResult.message }}</span>
          <div v-if="validationResult.errors" class="validation-errors">
            <div v-for="(error, index) in validationResult.errors" :key="index" class="error-item">
              {{ error }}
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>

    <div class="import-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button 
        type="primary" 
        @click="handleImport" 
        :loading="importing"
        :disabled="!canImport"
      >
        {{ importing ? '导入中...' : '开始导入' }}
      </el-button>
      <el-button @click="validateTemplate" :loading="validating">
        验证模板
      </el-button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TemplateImport',
  data() {
    return {
      importForm: {
        importType: 'file',
        file: null,
        jsonData: '',
        url: '',
        authToken: '',
        options: ['validate', 'includeData']
      },
      fileList: [],
      previewData: null,
      validationResult: null,
      activePreview: ['preview'],
      importing: false,
      validating: false,
      rules: {
        file: [
          { required: true, message: '请选择模板文件', trigger: 'change' }
        ],
        jsonData: [
          { required: true, message: '请输入模板JSON数据', trigger: 'blur' }
        ],
        url: [
          { required: true, message: '请输入模板URL地址', trigger: 'blur' },
          { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    canImport() {
      switch (this.importForm.importType) {
        case 'file':
          return this.importForm.file !== null
        case 'json':
          return this.importForm.jsonData.trim().length > 0
        case 'url':
          return this.importForm.url.trim().length > 0
        default:
          return false
      }
    }
  },
  watch: {
    'importForm.jsonData': {
      handler(newVal) {
        if (newVal.trim()) {
          this.debouncedParseJSON()
        }
      },
      immediate: false
    }
  },
  created() {
    // 防抖处理JSON解析
    this.debouncedParseJSON = this.$utils.debounce(this.parseJSON, 500)
  },
  methods: {
    /**
     * 处理导入方式变更
     */
    handleImportTypeChange() {
      this.previewData = null
      this.validationResult = null
      this.fileList = []
      this.importForm.file = null
    },

    /**
     * 处理文件选择
     */
    handleFileChange(file, fileList) {
      if (fileList.length > 0) {
        this.fileList = [fileList[fileList.length - 1]]
        this.importForm.file = file.raw
        
        // 读取文件内容
        this.readFileContent(file.raw)
      }
    },

    /**
     * 处理文件移除
     */
    handleFileRemove() {
      this.fileList = []
      this.importForm.file = null
      this.previewData = null
    },

    /**
     * 读取文件内容
     */
    readFileContent(file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        try {
          const content = e.target.result
          this.previewData = JSON.parse(content)
          this.validateTemplateStructure(this.previewData)
        } catch (error) {
          console.error('解析文件失败:', error)
          this.$message.error('文件格式错误，请检查文件内容')
        }
      }
      reader.readAsText(file)
    },

    /**
     * 解析JSON数据
     */
    parseJSON() {
      if (!this.importForm.jsonData.trim()) {
        this.previewData = null
        return
      }

      try {
        this.previewData = JSON.parse(this.importForm.jsonData)
        this.validateTemplateStructure(this.previewData)
      } catch (error) {
        console.error('解析JSON失败:', error)
        this.validationResult = {
          valid: false,
          message: 'JSON格式错误，请检查数据格式'
        }
      }
    },

    /**
     * 格式化JSON
     */
    formatJSON() {
      if (!this.importForm.jsonData.trim()) return

      try {
        const parsed = JSON.parse(this.importForm.jsonData)
        this.importForm.jsonData = JSON.stringify(parsed, null, 2)
        this.$message.success('JSON格式化完成')
      } catch (error) {
        this.$message.error('JSON格式错误，无法格式化')
      }
    },

    /**
     * 清空JSON
     */
    clearJSON() {
      this.importForm.jsonData = ''
      this.previewData = null
      this.validationResult = null
    },

    /**
     * 加载示例数据
     */
    loadExample() {
      const exampleTemplate = {
        name: '示例模板',
        type: 'record',
        pageSize: 'A4',
        components: [
          {
            id: 'header_1',
            type: 'header',
            position: { x: 0, y: 0, width: 794, height: 80 },
            content: {
              title: '检测报告模板',
              subtitle: '这是一个示例模板',
              showBorder: true
            }
          },
          {
            id: 'text_1',
            type: 'text',
            position: { x: 50, y: 100, width: 200, height: 30 },
            content: {
              text: '样品编号：',
              fontSize: 12
            }
          }
        ]
      }

      this.importForm.jsonData = JSON.stringify(exampleTemplate, null, 2)
      this.previewData = exampleTemplate
      this.validateTemplateStructure(exampleTemplate)
    },

    /**
     * 验证模板结构
     */
    validateTemplateStructure(templateData) {
      const errors = []

      // 基本字段验证
      if (!templateData.name) {
        errors.push('模板名称不能为空')
      }

      if (!templateData.type || !['record', 'report'].includes(templateData.type)) {
        errors.push('模板类型必须为 record 或 report')
      }

      if (!templateData.components || !Array.isArray(templateData.components)) {
        errors.push('模板必须包含组件数组')
      } else {
        // 验证组件结构
        templateData.components.forEach((comp, index) => {
          if (!comp.id) {
            errors.push(`组件 ${index + 1} 缺少ID`)
          }
          if (!comp.type) {
            errors.push(`组件 ${index + 1} 缺少类型`)
          }
          if (!comp.position || typeof comp.position !== 'object') {
            errors.push(`组件 ${index + 1} 位置信息不完整`)
          }
        })
      }

      this.validationResult = {
        valid: errors.length === 0,
        message: errors.length === 0 ? '模板结构验证通过' : '发现模板结构问题',
        errors: errors.length > 0 ? errors : null
      }

      return errors.length === 0
    },

    /**
     * 验证模板
     */
    async validateTemplate() {
      if (!this.previewData) {
        this.$message.warning('请先提供模板数据')
        return
      }

      this.validating = true
      try {
        // 模拟API验证
        await new Promise(resolve => setTimeout(resolve, 1000))
        
        const isValid = this.validateTemplateStructure(this.previewData)
        if (isValid) {
          this.$message.success('模板验证通过')
        } else {
          this.$message.warning('模板存在一些问题，请查看验证结果')
        }
      } catch (error) {
        console.error('验证模板失败:', error)
        this.$message.error('模板验证失败')
      } finally {
        this.validating = false
      }
    },

    /**
     * 处理导入
     */
    async handleImport() {
      // 表单验证
      try {
        await this.$refs.importForm.validate()
      } catch (error) {
        this.$message.warning('请完善导入信息')
        return
      }

      // 数据验证
      if (!this.previewData) {
        this.$message.warning('请先提供有效的模板数据')
        return
      }

      if (this.importForm.options.includes('validate') && !this.validationResult.valid) {
        this.$message.warning('模板验证未通过，请先解决相关问题')
        return
      }

      this.importing = true
      try {
        // 模拟API导入
        await new Promise(resolve => setTimeout(resolve, 1500))
        
        const importData = {
          template: this.previewData,
          options: this.importForm.options,
          importType: this.importForm.importType
        }

        this.$emit('import', importData)
        this.$message.success('模板导入成功')
      } catch (error) {
        console.error('导入模板失败:', error)
        this.$message.error('导入模板失败')
      } finally {
        this.importing = false
      }
    },

    /**
     * 处理取消
     */
    handleCancel() {
      this.$emit('cancel')
    },

    /**
     * 获取模板类型标签样式
     */
    getTemplateTypeTag(type) {
      const tagMap = {
        record: 'primary',
        report: 'success'
      }
      return tagMap[type] || 'info'
    },

    /**
     * 获取模板类型文本
     */
    getTemplateTypeText(type) {
      const textMap = {
        record: '原始记录',
        report: '检测报告'
      }
      return textMap[type] || '未知类型'
    },

    /**
     * 获取组件类型文本
     */
    getComponentTypeText(type) {
      const typeMap = {
        text: '文本',
        table: '表格',
        parameter: '参数',
        image: '图片',
        header: '页眉',
        footer: '页脚',
        signature: '签名'
      }
      return typeMap[type] || type
    },

    /**
     * 获取内容预览
     */
    getContentPreview(component) {
      if (!component.content) return '-'
      
      switch (component.type) {
        case 'text':
          return component.content.text || '-'
        case 'parameter':
          return component.content.paramCode || '-'
        case 'header':
          return component.content.title || '-'
        default:
          return JSON.stringify(component.content).substring(0, 50) + '...'
      }
    }
  }
}
</script>

<style scoped>
.template-import {
  padding: 0 10px;
}

.import-section {
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
  border: 1px solid #e6e8eb;
}

.template-upload {
  width: 100%;
}

.json-actions {
  margin-top: 10px;
  display: flex;
  gap: 10px;
}

.preview-info {
  font-size: 12px;
}

.components-preview {
  margin-top: 15px;
}

.components-preview h4 {
  margin: 0 0 10px 0;
  font-size: 13px;
  color: #606266;
}

.content-preview {
  font-size: 11px;
  color: #909399;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.validation-result {
  padding: 10px;
  border-radius: 4px;
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.validation-result.success {
  background: #f0f9ff;
  border: 1px solid #b3e19d;
  color: #67c23a;
}

.validation-result.error {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  color: #f56c6c;
}

.validation-errors {
  margin-top: 8px;
  padding-left: 20px;
}

.error-item {
  font-size: 12px;
  color: #f56c6c;
  margin-bottom: 4px;
}

.import-actions {
  margin-top: 20px;
  text-align: right;
  padding-top: 15px;
  border-top: 1px solid #e6e8eb;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .import-actions {
    flex-direction: column;
  }
  
  .import-actions .el-button {
    width: 100%;
  }
}
</style>